package org.lan.basic.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.inject.Inject;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.lan.basic.IBaseDao;

@SuppressWarnings("unchecked")
public class BaseDao<T> implements IBaseDao<T> {

	private SessionFactory sessionFactory;

	private Class<T> clazz;

	public BaseDao() {
		clazz = (Class<T>) (((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
	}

	@Inject
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public T save(T t) {
		T entity = t;
		getSession().save(entity);
		return entity;
	}

	@Override
	public T load(Serializable id) {
		return (T) getSession().load(clazz, id);
	}

	@Override
	public void delete(Serializable id) {
		getSession().delete(load(id));
	}

	@Override
	public void update(T t) {
		getSession().update(t);
	}

	private void setQuery(Query query, Object... args) {
		if (args != null && args.length > 0) {
			for (int i = 0; i < args.length; i++) {
				query.setParameter(i, args[i]);
			}
		}
	}

	@Override
	public List<?> list(String hql, Object... args) {
		Query query = getSession().createQuery(hql);
		setQuery(query, args);
		return query.list();
	}

	@Override
	public Object query(String hql, Object... args) {
		Query query = getSession().createQuery(hql);
		setQuery(query, args);
		return query.uniqueResult();
	}

	@Override
	public int update(String hql, Object... args) {
		Query query = getSession().createQuery(hql);
		setQuery(query, args);
		return query.executeUpdate();
	}
}
